package jschool.persistencia;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.swing.JOptionPane;

public class Conexion {
	private String username;
	private String password;
	private String url;
	public Connection con;
	private PreparedStatement stmt;
	private ResultSet rs;
	private static Conexion instancia = null;

	public Conexion() {
		Properties properties = new Properties();
		try {
			FileInputStream databaseData = new FileInputStream(
					"database.properties");
			properties.load(databaseData);
			databaseData.close();
			username = properties.getProperty("jdbc.username");
			password = properties.getProperty("jdbc.password");
			url = properties.getProperty("jdbc.url");
			con = DriverManager.getConnection(url, username, password);
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(null,
					"No se encontro el Archivo de Propiedades");
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null,
					"Error en el Flujo de Entrada y Salida");
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "Error de tipo SQL");
		}
	}

	public static Conexion getInstancia() {
		if (instancia == null) {
			instancia = new Conexion();
		}
		return instancia;
	}
	
	public void cerrarConexion() {
		try {
			con.close();
			rs.close();
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public Statement hacerEnunciado(String enunciado) {
		try {
			stmt = con.prepareStatement(enunciado);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}

	public ResultSet hacerConsulta(String consulta) {
		try {
			rs = stmt.executeQuery(consulta);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;

	}
	
	
	
	

}
